import os
import requests
from requests.exceptions import JSONDecodeError

organize_name = "open-harmony-edu-dist"     # 指定的组织
output_dir_name = "pr_out"                  # 指定的数据存放路径
output_dir = ""
access_token = ""                           # 替换为自己有效的access_token

# 获取PR信息
def get_pr_info(organize, repo, pr_no):
    files_url = f"https://gitee.com/api/v5/repos/{organize}/{repo}/pulls/{pr_no}/files?access_token={access_token}"
    files_list = []
    dir_path = f"{output_dir}/{organize}/{repo}/pr{pr_no}"

    if os.path.exists(dir_path):
        return None

    try:
        response = requests.get(files_url)
        response.raise_for_status()
    except JSONDecodeError as e:
        print(f"JSON解析失败: {e}")
        print(f"原始内容: {response.text[:200]}")
        return None
    files_json = response.json()

    files_num = len(files_json)
    if files_num == 0:
        return None
    
    os.makedirs(dir_path, exist_ok=True)
    files_no = 1
    for file in files_json:
        if file["patch"]["new_file"] is True:
            files_list.append(f"New file {file["patch"]["new_path"]}")
        elif file["patch"]["deleted_file"] is True:
            files_list.append(f"Del file {file["patch"]["old_path"]}")
        elif file["patch"]["renamed_file"] is True:
            files_list.append(f"Rename file {file["patch"]["old_path"]} to {file["patch"]["new_path"]}")
        else:
            files_list.append(f"Modify file {file["patch"]["new_path"]}")
        with open(f"{dir_path}/patch{files_no}", 'w') as f:
            f.write(f"+++ {file["patch"]["new_path"]}\n")
            f.write(f"--- {file["patch"]["old_path"]}\n")
            f.write(f"{file["patch"]["diff"]}")
        files_no += 1
    return files_list

# 获取仓库所有PR列表
def get_repo_prs(organize, repo):
    pg = 1
    file_path = f"{output_dir}/{organize}/{repo}/pr_list.txt"

    while True:
        prs_url = f"https://gitee.com/api/v5/repos/{organize}/{repo}/pulls?state=all&per_page=100&page={pg}&access_token={access_token}"

        try:
            response = requests.get(prs_url)
            response.raise_for_status()
        except JSONDecodeError as e:
            print(f"JSON解析失败: {e}")
            print(f"原始内容: {response.text[:200]}")
            return None
        
        prs_json = response.json()
        prs_num = len(prs_json)
        pg += 1

        if prs_num == 0:
            break

        if not os.path.exists(os.path.dirname(file_path)):
            os.makedirs(os.path.dirname(file_path), exist_ok=True)
            with open(file_path, 'w') as f:
                f.write(f"{repo}:\n")
        
        for pr in prs_json:
            pr_no = pr["number"]
            files_list = get_pr_info(organize, repo, pr_no)
            if files_list is None:
                continue
            # 写入文件
            with open(file_path, 'a') as f:
                f.write(f"\tpr{pr_no}:\n")
                for file in files_list:
                    f.write(f"\t\t{file}\n")

# 获取组织所有仓库的PR
def get_repos(organize):
    pg = 1
    repos_no = 0

    # 清空上次内容
    if os.path.exists(f"{output_dir}/{organize}/pr_list.txt"):
        with open(f"{output_dir}/{organize}/pr_list.txt", 'w') as f:
            pass

    while True:
        repos_url = f"https://gitee.com/api/v5/orgs/{organize}/repos?per_page=100&page={pg}&access_token={access_token}"

        # gitee 有访问频率限制，访问过多会触发403
        try:
            response = requests.get(repos_url)
            response.raise_for_status()
        except JSONDecodeError as e:
            print(f"JSON解析失败: {e}")
            print(f"原始内容: {response.text[:200]}")
            return None
        
        repos_json = response.json()
        repos_num =  len(repos_json)

        if repos_num == 0:
            break

        pg += 1
        # 获取仓库名
        for repo in repos_json:
            # 获取仓库所有PR
            repos_no += 1
            repo_name = repo["name"]
            print(f"{repos_no}: Processing repo {repo_name}")
            #get_repo_prs(organize, repo_name)
            if not os.path.exists(f"{output_dir}/{organize}/{repo_name}/pr_list.txt"):
                continue
            with open(f"{output_dir}/{organize}/{repo_name}/pr_list.txt", 'r') as src, open(f"{output_dir}/{organize}/pr_list.txt", 'a') as dst:
                for line in src:
                    dst.write(line)
                dst.write("\n")


current_dir = os.getcwd()
output_dir = f"{current_dir}/{output_dir_name}"
get_repos(organize_name)